package com.springboot.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.dao.DishMapper;
import com.springboot.pojo.Dish;
import com.springboot.pojo.DishDto;
import com.springboot.pojo.DishFlavor;
import com.springboot.service.DishFlavorService;
import com.springboot.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    /**
     * 新增菜品同时保存口味数据
     * @param dishDto
     */
    @Transactional
    @Override
    public void saveWithFlavors(DishDto dishDto) {
        //保存菜品的基本信息
        this.save(dishDto);
       //获取菜品的id
        Long dishId = dishDto.getId();
        //用stream流遍历口味列表，并保存到数据库
        List<DishFlavor> flavors = dishDto.getFlavors();
         flavors=flavors.stream().map(item->{item.setDishId(dishId);return item;})
                 .collect(Collectors.toList());
        //保存菜品的口味信息
        dishFlavorService.saveBatch(flavors);
    }
    //根据id查询菜品信息和口味信息
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品基本信息
        Dish dish = this.getById(id);
        DishDto dishDto=new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        //查询当前菜品口味信息
        LambdaQueryWrapper<DishFlavor> wrapper=new LambdaQueryWrapper();
        wrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> list = dishFlavorService.list(wrapper);
         dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
         //更新菜品表基本信息
        this.updateById(dishDto);
        //清理之前口味信息
        LambdaQueryWrapper<DishFlavor> wrapper=new LambdaQueryWrapper();
        wrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(wrapper);
        //更新口味表信息
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.stream().map((item)->{
             item.setDishId(dishDto.getId());
             return  item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);

    }


}
